package com.java.vue.controller;

import com.java.vue.entity.User;
import com.java.vue.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * description:
 * author:张腾
 * date:2021-02-10
 */

@RestController
@CrossOrigin
@RequestMapping("user")
public class UserController {

    @Autowired
    private UserService userService;

    @GetMapping("findAll")
    public Map<String,Object> findAll(Integer page,Integer rows){
        Map<String,Object> map = new HashMap<>();
        List<User> result = userService.findAll();
        map.put("total",10);
        map.put("totalPage",1);
        map.put("page",page);
        map.put("result",result);
        return map;
    }

    @GetMapping("findOne")
    public User findOne(long id){
        return userService.findById(id);
    }

    @PostMapping("add")
    public Map<String,Object> add(@RequestBody User user){
        Map<String,Object> map = new HashMap<>();
        try{
            userService.save(user);
            map.put("success",true);
            map.put("msg","添加用户成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","添加用户失败"+e.getMessage());
        }
        return map;
    }

    @PostMapping("edit")
    public Map<String,Object> edit(@RequestBody User user){
        Map<String,Object> map = new HashMap<>();
        try{
            userService.update(user);
            map.put("success",true);
            map.put("msg","修改用户信息成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","修改用户信息失败"+e.getMessage());
        }
        return map;
    }

    @GetMapping("del")
    public Map<String,Object> del(long id){
        Map<String,Object> map = new HashMap<>();
        try{
            userService.delete(id);
            map.put("success",true);
            map.put("msg","删除用户成功");
        }catch (Exception e){
            e.printStackTrace();
            map.put("success",false);
            map.put("msg","删除用户失败"+e.getMessage());
        }
        return map;
    }
}
